﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
using System.Net;
using X23.Application.UserManagement;
using X23.Application.Dto;

namespace X23.Extensions.MiddlewareExtensions
{
    /// <summary>
    /// 错误处理中间件
    /// </summary>
    public class ErrorHandlingMiddleware: IMiddleware
    {
        private readonly ILoggerFactory _loggerFactory;

        public ErrorHandlingMiddleware(ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;
        }

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex, _loggerFactory);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception exception, ILoggerFactory loggerFactory)
        {
            var logger = loggerFactory.CreateLogger("HandleException");
            logger.LogError(exception, exception.Message);

            var code = HttpStatusCode.InternalServerError;
            //context.Response.ContentType = "text/html;charset=utf-8";
            context.Response.StatusCode = (int)code;
            return context.Response.WriteAsJsonAsync(new ResponseDto { Code = (int)code, ErrorMsg = exception.Message, StackTrace = exception.StackTrace });
            //return context.Response.WriteAsync("服务器错误，错误信息：" + exception.Message);
        }
    }

    //public class ErrorHandlingMiddleware
    //{
    //    private readonly RequestDelegate _next;

    //    public ErrorHandlingMiddleware(RequestDelegate next)
    //    {
    //        _next = next;
    //    }

    //    public async Task Invoke(HttpContext context, IUserManagementService userManagementService, ILoggerFactory loggerFactory)
    //    {
    //        try
    //        {
    //            await _next(context);
    //        }
    //        catch (Exception ex)
    //        {
    //            await userManagementService.AddAsync(new Application.UserManagement.Dto.UserDto { Name = "A ERROR" });
    //            await HandleExceptionAsync(context, ex, loggerFactory);
    //        }
    //    }

    //    private Task HandleExceptionAsync(HttpContext context, Exception exception, ILoggerFactory loggerFactory)
    //    {
    //        var logger = loggerFactory.CreateLogger("HandleException");
    //        logger.LogError(exception, exception.Message);

    //        var code = HttpStatusCode.InternalServerError;
    //        context.Response.ContentType = "text/html;charset=utf-8";
    //        context.Response.StatusCode = (int)code;
    //        return context.Response.WriteAsync("服务器错误，错误信息：" + exception.Message);
    //    }
    //}
}
